var socketio = require('socket.io')

var io
var guestNumber = 0
var nickNames = {}
var namesUsed = []
var currentRoom = {}

exports.listen = function(server) {
  io = socketio(server)
  io.on('connection', function(socket) {
    console.log('socket 连接成功 aaaaaaa')
    var addedUser = false //是否已经加入新成员

    socket.on('create room', room => {
      socket.join(room, () => {
        let rooms = Object.keys(socket.rooms)
        currentRoom[socket.id] = room
        socket.emit('after created', {
          success: true,
          room: room
        })
      })
    })

    socket.on('change room', room => {
      socket.leave(currentRoom[socket.id])
      io.in(currentRoom[socket.id]).clients((err, clients) => {
        if (err) throw err
        socket.to(currentRoom[socket.id]).emit('user leave', {
          username: socket.username,
          guestNumber: clients.length
        })
      })
      addedUser = false
      socket.emit('create room', room)
    })

    socket.on('add user', username => {
      if (addedUser) return
      //we store the username in the socket session for this client
      socket.username = username

      //store the username in nickNames Object
      nickNames[socket.id] = username
      //guestNumber + 1
      ++guestNumber
      addedUser = true
      //获取一系列连接到当前命名空间（路由）的客户端ID（会穿越所有节点）
      var room = currentRoom[socket.id]
      io.in(currentRoom[socket.id]).clients((err, clients) => {
        if (err) throw err
        var client = clients.length

        socket.emit('enter', {
          curRoom: currentRoom[socket.id],
          guestNumber: clients.length
        })
        socket.to(currentRoom[socket.id]).emit('user joined', {
          username: socket.username,
          guestNumber: clients.length
        })
      })
    })

    socket.on('new message', data => {
      socket.to(currentRoom[socket.id]).emit('new message', {
        username: socket.username,
        message: data
      })
    })

    socket.on('disconnect', () => {
      if (addedUser) {
        var nameIndex = namesUsed.indexOf(socket.username)
        delete namesUsed[nameIndex]
        delete nickNames[socket.id]
        // --guestNumber
        io.in(currentRoom[socket.id]).clients((err, clients) => {
          if (err) throw err
          socket.to(currentRoom[socket.id]).emit('user leave', {
            username: socket.username,
            guestNumber: clients.length
          })
        })
      }
    })
  })
}
